package curd

import (
	"backend/databases"
	"backend/models"
	"backend/utils"
	"gorm.io/gorm"
)

func GetUserByUsernamePassword(username string, password string) (*models.SysUser, error) {
	data := new(models.SysUser)
	// err := databases.DB.Where("username = ? AND password = ?", username, password).First(data).Error
	err := databases.DB.Where("username = ?", username).First(data).Error
	mach := utils.CompareHashAndPassword(data.Password, password)
	if mach != nil {
		return nil, mach
	}
	return data, err

}

// 获取管理员的数据列表
func GetUserList(keyward string) *gorm.DB {
	tx := databases.DB.Model(new(models.SysUser)).Select("id,username,phone,avatar,created_at,updated_at")
	if keyward != "" {
		tx = tx.Where("username LIKE ?", "%"+keyward+"%")
	}
	return tx
}

// 根据id获取管理员信息
func GetUserDetail(id uint) (*models.SysUser, error) {
	su := new(models.SysUser)
	err := databases.DB.Model(new(models.SysUser)).Where("id = ?", id).First(su).Error
	return su, err
}

// 获取角色列表数据
func GetRoleList(keyward string) *gorm.DB {
	tx := databases.DB.Model(new(models.SysRole)).Select("id,name,is_admin,sort,created_at,updated_at")
	if keyward != "" {
		tx = tx.Where("name LIKE ?", "%"+keyward+"%")
	}
	tx.Order("sort ASC")
	return tx
}

// 根据id获取角色信息
func GetRoleDetail(id uint) (*models.SysRole, error) {
	sr := new(models.SysRole)
	err := databases.DB.Model(new(models.SysRole)).Where("id = ?", id).First(sr).Error
	return sr, err
}

// GetMenuList 获取所有菜单数据
func GetMenuList() *gorm.DB {
	tx := databases.DB.Model(new(models.SysMenu)).Select("id,name,icon,sort,path,level,component_name").Order("sort ASC")
	return tx
}

// GetRoleMenuId 获取指定角色的菜单
func GetRoleMenuId(roleId uint, isAdmin bool) ([]uint, error) {
	tx := new(gorm.DB)
	data := make([]uint, 0)
	if isAdmin {
		tx = databases.DB.Model(new(models.SysMenu)).Select("id").Order("sort ASC")
	} else {
		tx = databases.DB.Model(new(models.RoleMenu)).Select("sm.id").Joins("LEFT JOIN sys_menu sm on sm.id=sys_role_menu.menu_id").
			Where("sys_role_menu.role_id = ?", roleId).Order("sm.sort ASC")
	}
	err := tx.Scan(&data).Error
	return data, err
}

// GetRoleMenus 根据角色ID获取所有菜单数据列表
func GetRoleMenus(roleId uint, isAdmin bool) (*gorm.DB, error) {
	tx := new(gorm.DB)
	if isAdmin {
		tx = databases.DB.Model(new(models.SysMenu)).Select("id,parent_id, component_name,name,icon,sort,path,level").Order("sort ASC")
	} else {
		roleBasic := new(models.SysRole)
		err := databases.DB.Model(new(models.SysRole)).Select("id").Where("id = ?", roleId).First(roleBasic).Error
		if err != nil {
			return nil, err
		}
		tx = databases.DB.Model(new(models.RoleMenu)).Select("mb.id, mb.parent_id, mb.component_name, mb.name, mb.icon, mb.sort, mb.path, mb.level").
			Joins("LEFT JOIN sys_menu mb on mn.id = sys_role_menu.menu_id").
			Where("sys_role_menu.role_id = ?", roleBasic.ID).Order("mb.sort ASC")
	}
	return tx, nil
}
